package com.github.chxiaowu.mongo;

import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.FindOneAndUpdateOptions;

public class MongoHelper {

	static Logger LOG = LoggerFactory.getLogger(MongoHelper.class);

	private String uri;
	private MongoClient mongoClient;
	private MongoDatabase database;
	private MongoClientURI mongoURI;

	public void init() {
		mongoURI = new MongoClientURI(uri);
		mongoClient = new MongoClient(mongoURI);
		// mongodb 驱动 3.6还是几版本开始，提供了 POJO Codec,
		// 一般的简单对象可以自动 映射， 也可以注册自定义的映射规则
		CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry(),
				CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()));
		database = mongoClient.getDatabase(mongoURI.getDatabase()).withCodecRegistry(pojoCodecRegistry);
	}

	public void destroy() {
		if (mongoClient != null) {
			LOG.info("closing the db collection...closed");
			mongoClient.close();
		}
	}

	public MongoCollection<Document> getCollection(String name) {
		return database.getCollection(name);

	}

	public <TDocument> MongoCollection<TDocument> getCollection(String name, Class<TDocument> clazz) {
		return database.getCollection(name, clazz);
	}

	public int nextValue(String counterName) {
		Document filter = new Document("name", counterName);
		Document fields = new Document("value", true);
		Document update = new Document("$inc", new Document("value", 1));

		FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().projection(fields).upsert(true);
		Document newObj = database.getCollection("counter").findOneAndUpdate(filter, update, options);
		if (newObj == null) {
			return 0;
		} else {
			return newObj.getInteger("value");
		}
	}

	// public String getUri() {
	// return uri;
	// }

	public void setUri(String uri) {
		this.uri = uri;
	}
	//
	// public MongoClient getMongoClient() {
	// return mongoClient;
	// }
	//
	// public MongoClientURI getMongoURI() {
	// return mongoURI;
	// }

	// public MongoDatabase getDatabase() {
	// return database;
	// }

}
